package com.example.cloudcashierpos.net;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.media.Ringtone;

import com.example.cloudcashierpos.app.Constants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.fastjson.FastJsonConverterFactory;

public class BaseApplication extends Application {
    // 提供一个单例，初始化Retrofit
    private static BaseApplication mInstance = null;

    private SQLiteDatabase db;
    private String machine;//手持机编码
    private Ringtone r;
    private Retrofit retrofit;
    private static Context mContext;

    // public static BaseApplication getInstance,指BaseApplication类的getInstance可以拿到BaseApplication类里面的方法
    public static BaseApplication getInstance() {
        if (mInstance == null) {
            mInstance = new BaseApplication();
        }
        return mInstance;
    }

    //加载数据库驱动
    static {
        try {
            String driverName1 = "net.sourceforge.jtds.jdbc.Driver";
            String driverName = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName1);
            Class.forName(driverName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        mContext = getApplicationContext();
    }

    public static Context getContext() {
        return mContext;
    }

    public Retrofit getRetrofit() {
        if (retrofit == null) {
            // 设置日志拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            // 打印响应日志，现在okhttp里面设置，在加入到Retrofit里面
            OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(Constants.BASE_URL) // 线上
//                    .baseUrl(Constants.MAIN_URL) // 本地
                    .addConverterFactory(FastJsonConverterFactory.create()) // 在控制台输出请求
                    .client(client)
                    .build();
        }
        // 将retrofit返回，可以获取同步或异步数据的回调
        return retrofit;
    }

    /**
     * 播放扫描声音
     * <p>
     * Play scanning
     */
    public void song() {
        if (r.isPlaying()) {
            r.stop();
        }
        r.play();
    }
}
